// SimpleNote 主应用文件

// 编译时配置（构建时会被替换）
const COMPILATION_KEY = "dev-key-2024";
const VERSION_ID = "v1.0.0-dev";
const DISTRIBUTION = "development";

// 应用配置
const APP_CONFIG = {
  name: 'SimpleNote',
  version: VERSION_ID,
  distribution: DISTRIBUTION,
  compilationKey: COMPILATION_KEY
};

// 加密工具类
class CryptoUtils {
  constructor() {
    this.compilationKey = COMPILATION_KEY;
    this.versionId = VERSION_ID;
  }

  // 生成用户密钥
  async generateUserKey(platform) {
    // 基础密钥（基于平台）
    const baseKey = await this.generateBaseKey(platform);
    
    // 编译时密钥
    const compilationKey = await this.generateCompilationKey();
    
    // 组合密钥
    const combinedKey = await this.combineKeys(baseKey, compilationKey);
    
    console.log('密钥生成调试信息:', {
      platform: platform,
      baseKeyLength: baseKey.byteLength,
      compilationKeyLength: compilationKey.byteLength,
      combinedKeyLength: combinedKey.byteLength,
      baseKeyHex: Array.from(new Uint8Array(baseKey)).map(b => b.toString(16).padStart(2, '0')).join('').substring(0, 16) + '...',
      compilationKeyHex: Array.from(new Uint8Array(compilationKey)).map(b => b.toString(16).padStart(2, '0')).join('').substring(0, 16) + '...',
      combinedKeyHex: Array.from(new Uint8Array(combinedKey)).map(b => b.toString(16).padStart(2, '0')).join('').substring(0, 16) + '...'
    });
    
    // 将哈希结果转换为 CryptoKey
    return await this.importKey(combinedKey);
  }

  // 生成基础密钥
  async generateBaseKey(platform) {
    const salt = `simplenote_${platform}_v1`;
    const encoder = new TextEncoder();
    const data = encoder.encode(salt);
    return await crypto.subtle.digest('SHA-256', data);
  }
  

  // 生成编译时密钥
  async generateCompilationKey() {
    const salt = `compilation_${this.compilationKey}_${this.versionId}`;
    const encoder = new TextEncoder();
    const data = encoder.encode(salt);
    return await crypto.subtle.digest('SHA-256', data);
  }

  // 组合密钥
  async combineKeys(baseKey, compilationKey) {
    const combined = new Uint8Array(baseKey.byteLength + compilationKey.byteLength);
    combined.set(new Uint8Array(baseKey), 0);
    combined.set(new Uint8Array(compilationKey), baseKey.byteLength);
    
    return await crypto.subtle.digest('SHA-256', combined);
  }

  // 将哈希结果导入为 CryptoKey
  async importKey(keyData) {
    // 确保密钥长度为256位（32字节）
    let finalKeyData = keyData;
    if (keyData.byteLength !== 32) {
      // 如果长度不是32字节，使用PBKDF2派生密钥
      const salt = new TextEncoder().encode('simplenote_salt_v1');
      finalKeyData = await crypto.subtle.deriveBits(
        {
          name: 'PBKDF2',
          salt: salt,
          iterations: 100000,
          hash: 'SHA-256'
        },
        await crypto.subtle.importKey(
          'raw',
          keyData,
          { name: 'PBKDF2' },
          false,
          ['deriveBits']
        ),
        256
      );
    }
    
    return await crypto.subtle.importKey(
      'raw',
      finalKeyData,
      { name: 'AES-GCM' },
      false,
      ['encrypt', 'decrypt']
    );
  }

  // 生成随机IV
  generateIV() {
    return crypto.getRandomValues(new Uint8Array(12));
  }

  // 加密文本
  async encryptText(text, key) {
    const encoder = new TextEncoder();
    const iv = this.generateIV();
    
    const encrypted = await crypto.subtle.encrypt(
      {
        name: 'AES-GCM',
        iv: iv
      },
      key,
      encoder.encode(text)
    );
    
    // 将IV和密文组合
    const result = new Uint8Array(iv.length + encrypted.byteLength);
    result.set(iv, 0);
    result.set(new Uint8Array(encrypted), iv.length);
    
    return btoa(String.fromCharCode(...result));
  }

  // 解密文本
  async decryptText(encryptedData, key) {
    const decoder = new TextDecoder();
    const data = new Uint8Array(atob(encryptedData).split('').map(c => c.charCodeAt(0)));
    
    // 提取IV和密文
    const iv = data.slice(0, 12);
    const encrypted = data.slice(12);
    
    const decrypted = await crypto.subtle.decrypt(
      {
        name: 'AES-GCM',
        iv: iv
      },
      key,
      encrypted
    );
    
    return decoder.decode(decrypted);
  }
}

// Git 平台适配器
class GitPlatformAdapter {
  constructor(platform, token, username, repo) {
    this.platform = platform;
    this.token = token;
    this.username = username;
    this.repo = repo;
    this.maxFileSize = 500000; // 单个文件最大字符数（约500KB）
    this.setupAPI();
  }

  setupAPI() {
    // 只支持Gitee
    this.baseURL = 'https://gitee.com/api/v5';
    this.authHeader = `token ${this.token}`;
    this.useUrlAuth = true;   // Gitee使用URL参数认证
  }

  // 同步笔记到Git
  async syncNotes(notes) {
    // 检查网络连接
    if (!navigator.onLine) {
      throw new Error('网络连接已断开，请检查网络后重试');
    }
    
    // 将笔记分割成多个文件
    const noteFiles = this.splitNotesIntoFiles(notes);
    
    const results = [];
    
    // 并行处理所有文件
    const syncPromises = Object.entries(noteFiles).map(async ([fileName, fileNotes]) => {
      const content = btoa(JSON.stringify(fileNotes));
      let url = `${this.baseURL}/repos/${this.username}/${this.repo}/contents/${fileName}`;
      
      // Gitee使用URL参数认证
      url += `?access_token=${this.token}`;
      
      // 重试机制
      let retryCount = 0;
      const maxRetries = 2;
      
      while (retryCount <= maxRetries) {
        try {
          // 每次都重新获取最新的文件信息，确保使用最新的SHA值
          console.log(`获取文件 ${fileName} 的最新信息 (尝试 ${retryCount + 1}/${maxRetries + 1})`);
          const existingFile = await this.getFileInfo(fileName);
          
          const body = {
            message: `Update notes - ${new Date().toISOString()}`,
            content: content
          };
          
          if (existingFile) {
            body.sha = existingFile.sha;
          }
          
          // 根据文件是否存在决定使用POST还是PUT
          const method = existingFile ? 'PUT' : 'POST';
          
          console.log('发送同步请求:', {
            url: url,
            method: method,
            fileName: fileName,
            fileExists: !!existingFile,
            notesCount: Object.keys(fileNotes).length,
            sha: existingFile ? existingFile.sha.substring(0, 8) + '...' : 'N/A',
            retryCount: retryCount,
            tokenLength: this.token.length,
            tokenPrefix: this.token.substring(0, 10) + '...',
            bodySize: JSON.stringify(body).length,
            platform: this.platform,
            username: this.username,
            repo: this.repo
          });
          
          const headers = {
            'Content-Type': 'application/json'
          };

          const response = await fetch(url, {
            method: method,
            headers: headers,
            body: JSON.stringify(body)
          });
          
          if (!response.ok) {
            const errorText = await response.text();
            console.error('同步请求失败:', {
              status: response.status,
              statusText: response.statusText,
              url: url,
              fileName: fileName,
              errorText: errorText,
              requestBody: JSON.stringify(body),
              retryCount: retryCount,
              platform: this.platform,
              username: this.username,
              repo: this.repo
            });

            // 如果是422错误且包含SHA相关错误，且还有重试次数，则重试
            if (response.status === 422 && 
                (errorText.includes('sha') || errorText.includes('SHA')) && 
                retryCount < maxRetries) {
              console.log(`SHA不匹配，准备重试 ${retryCount + 1}/${maxRetries}`);
              retryCount++;
              await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒
              continue;
            }

            let errorMessage = `同步失败: ${response.status} ${response.statusText}`;

            if (response.status === 401) {
              errorMessage = '认证失败，请检查访问令牌是否有效';
            } else if (response.status === 403) {
              errorMessage = '权限不足，请检查仓库访问权限';
            } else if (response.status === 404) {
              errorMessage = `仓库不存在: ${this.username}/${this.repo}，请检查仓库名称`;
            } else if (response.status === 422) {
              // 422错误通常是SHA不匹配或数据格式问题
              if (errorText.includes('sha') || errorText.includes('SHA')) {
                errorMessage = '文件已被其他操作修改，请重试';
              } else {
                errorMessage = '数据格式错误，请重试';
              }
            }

            throw new Error(errorMessage);
          }

          return await response.json();
        } catch (error) {
          console.error(`同步文件 ${fileName} 失败 (重试 ${retryCount}/${maxRetries}):`, error);
          
          // 如果是网络错误且还有重试次数，则重试
          if ((error.name === 'TypeError' && error.message.includes('fetch')) && 
              retryCount < maxRetries) {
            retryCount++;
            await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒
            continue;
          }
          
          if (error.name === 'TypeError' && error.message.includes('fetch')) {
            throw new Error('网络请求失败，请检查网络连接或稍后重试');
          } else if (error.message.includes('Failed to fetch')) {
            throw new Error('网络连接失败，请检查网络设置');
          }
          
          throw error;
        }
      }
    });
    
    // 等待所有文件同步完成
    try {
      const results = await Promise.all(syncPromises);
      return results;
    } catch (error) {
      console.error('批量同步失败:', error);
      throw error;
    }
  }
  
  // 将笔记分割成多个文件
  splitNotesIntoFiles(notes) {
    const noteEntries = Object.entries(notes);
    const files = {};
    
    console.log(`开始分割笔记，总数: ${noteEntries.length}，最大文件大小: ${this.maxFileSize} 字符`);
    
    // 按创建时间排序，确保分割的一致性
    noteEntries.sort((a, b) => {
      const timeA = new Date(a[1].createdAt || 0).getTime();
      const timeB = new Date(b[1].createdAt || 0).getTime();
      return timeA - timeB;
    });
    
    let currentFileIndex = 0;
    let currentFileNotes = {};
    let currentFileSize = 0;
    
    for (const [noteId, note] of noteEntries) {
      const noteSize = JSON.stringify(note).length;
      
      console.log(`处理笔记 ${noteId}，大小: ${noteSize} 字符，当前文件大小: ${currentFileSize} 字符`);
      
      // 如果当前文件已满（文件大小），创建新文件
      if (currentFileSize + noteSize > this.maxFileSize && Object.keys(currentFileNotes).length > 0) {
        const fileName = currentFileIndex === 0 ? 'notes.json' : `notes_${currentFileIndex}.json`;
        files[fileName] = { ...currentFileNotes };
        console.log(`创建新文件 ${fileName}，包含 ${Object.keys(currentFileNotes).length} 个笔记，大小: ${currentFileSize} 字符`);
        currentFileIndex++;
        currentFileNotes = {};
        currentFileSize = 0;
      }
      
      currentFileNotes[noteId] = note;
      currentFileSize += noteSize;
    }
    
    // 添加最后一个文件
    if (Object.keys(currentFileNotes).length > 0) {
      const fileName = currentFileIndex === 0 ? 'notes.json' : `notes_${currentFileIndex}.json`;
      files[fileName] = currentFileNotes;
      console.log(`创建最后文件 ${fileName}，包含 ${Object.keys(currentFileNotes).length} 个笔记，大小: ${currentFileSize} 字符`);
    }
    
    console.log(`笔记已分割为 ${Object.keys(files).length} 个文件:`, Object.keys(files));
    return files;
  }

  // 从Git获取笔记
  async getNotes() {
    // 检查网络连接
    if (!navigator.onLine) {
      throw new Error('网络连接已断开，请检查网络后重试');
    }
    
    let url = `${this.baseURL}/repos/${this.username}/${this.repo}/contents/%2F`;
    
    // Gitee使用URL参数认证
    url += `?access_token=${this.token}`;
    
    try {
      const response = await fetch(url);
      
      if (!response.ok) {
        let errorMessage = `获取文件列表失败: ${response.status} ${response.statusText}`;
        
        if (response.status === 401) {
          errorMessage = '认证失败，请检查访问令牌是否有效';
        } else if (response.status === 403) {
          errorMessage = '权限不足，请检查仓库访问权限';
        } else if (response.status === 404) {
          errorMessage = '仓库不存在，请检查仓库名称';
        }
        
        throw new Error(errorMessage);
      }
      
      const fileList = await response.json();
      
      // 过滤出笔记文件（以notes开头的.json文件）
      const noteFiles = fileList.filter(file => 
        file.type === 'file' && file.name.startsWith('notes') && file.name.endsWith('.json')
      );
      
      console.log(`找到 ${noteFiles.length} 个笔记文件:`, noteFiles.map(f => f.name));
      
      const allNotes = {};
      
      // 并行获取所有笔记文件的内容
      const filePromises = noteFiles.map(file => this.getNotesFromFile(file.name));
      const fileResults = await Promise.all(filePromises);
      
      // 合并所有笔记
      fileResults.forEach(fileNotes => {
        Object.assign(allNotes, fileNotes);
      });
      
      console.log(`从 ${noteFiles.length} 个文件中获取了 ${Object.keys(allNotes).length} 个笔记`);
      return allNotes;
    } catch (error) {
      console.error('获取笔记失败:', error);
      
      // 处理不同类型的错误
      if (error.name === 'TypeError' && error.message.includes('fetch')) {
        throw new Error('网络请求失败，请检查网络连接或稍后重试');
      } else if (error.message.includes('Failed to fetch')) {
        throw new Error('网络连接失败，请检查网络设置');
      }
      
      throw error;
    }
  }


  // 从单个文件获取笔记
  async getNotesFromFile(fileName) {
    let url = `${this.baseURL}/repos/${this.username}/${this.repo}/raw/${fileName}`;
    
    // Gitee使用URL参数认证
    url += `?access_token=${this.token}`;
    
    try {
      const response = await fetch(url);
      
      if (response.status === 404) {
        // 文件不存在，返回空对象
        return {};
      }
      
      if (!response.ok) {
        throw new Error(`获取文件 ${fileName} 失败: ${response.status} ${response.statusText}`);
      }
      
      const content = await response.text();
      return JSON.parse(content);
    } catch (error) {
      if (error.message.includes('404')) {
        // 文件不存在，返回空对象
        return {};
      }
      console.error(`获取文件 ${fileName} 失败:`, error);
      throw error;
    }
  }

  // 获取文件信息
  async getFileInfo(fileName = 'notes.json') {
    // 检查网络连接
    if (!navigator.onLine) {
      return null;
    }
    
    let url = `${this.baseURL}/repos/${this.username}/${this.repo}/contents/${fileName}`;
    
    // Gitee使用URL参数认证
    url += `?access_token=${this.token}`;
    
    try {
      const response = await fetch(url);
      
      if (response.status === 404) {
        return null;
      }
      
      if (!response.ok) {
        // 对于获取文件信息，我们静默处理错误，返回null
        console.warn(`获取文件信息失败: ${response.status} ${response.statusText}`);
        return null;
      }
      
      const fileInfo = await response.json();
      console.log(`获取文件 ${fileName} 信息:`, {
        fileName: fileName,
        sha: fileInfo.sha ? fileInfo.sha.substring(0, 8) + '...' : 'N/A',
        size: fileInfo.size,
        path: fileInfo.path,
        url: fileInfo.url
      });
      return fileInfo;
    } catch (error) {
      console.warn('获取文件信息失败:', error);
      return null;
    }
  }

  // 验证令牌
  async validateToken() {
    // 检查网络连接
    if (!navigator.onLine) {
      throw new Error('网络连接已断开，请检查网络后重试');
    }
    
    let url = `${this.baseURL}/user`;
    
    // Gitee使用URL参数认证
    url += `?access_token=${this.token}`;
    
    try {

      const response = await fetch(url);
      
      if (!response.ok) {
        let errorMessage = '令牌无效或已过期';
        
        if (response.status === 401) {
          errorMessage = '访问令牌无效，请检查令牌是否正确';
        } else if (response.status === 403) {
          errorMessage = '访问令牌权限不足，请检查令牌权限';
        }
        
        throw new Error(errorMessage);
      }
      
      return await response.json();
    } catch (error) {
      console.error('令牌验证失败:', error);
      
      // 处理不同类型的错误
      if (error.name === 'TypeError' && error.message.includes('fetch')) {
        throw new Error('网络请求失败，请检查网络连接或稍后重试');
      } else if (error.message.includes('Failed to fetch')) {
        throw new Error('网络连接失败，请检查网络设置');
      }
      
      throw error;
    }
  }
}

// 账户管理类
class AccountManager {
  constructor() {
    this.accounts = new Map();
    this.currentAccount = null;
    this.crypto = new CryptoUtils();
    this.loadAccounts();
  }

  // 创建账户
  async createAccount(name, platform, token, username, repo) {
    const id = this.generateAccountId();
    
    // 验证令牌
    const adapter = new GitPlatformAdapter(platform, token, username, repo);
    const userInfo = await adapter.validateToken();
    
    const account = {
      id,
      name,
      platform,
      token,
      username,
      repo,
      userInfo,
      createdAt: Date.now(),
      lastUsed: Date.now(),
      notes: {},
      settings: {
        autoSync: true,
        syncInterval: 300000, // 5分钟
        theme: 'light',
        fontSize: 16
      }
    };
    
    this.accounts.set(id, account);
    await this.saveAccounts();
    return account;
  }

  // 切换账户
  async switchAccount(accountId) {
    const account = this.accounts.get(accountId);
    if (!account) {
      throw new Error('账户不存在');
    }
    
    // 保存当前账户数据
    if (this.currentAccount) {
      await this.saveCurrentAccountData();
    }
    
    // 切换到新账户
    this.currentAccount = account;
    account.lastUsed = Date.now();
    
    // 加载账户数据
    await this.loadAccountData(account);
    
    await this.saveAccounts();
    return account;
  }

  // 删除账户
  async deleteAccount(accountId) {
    const account = this.accounts.get(accountId);
    if (!account) {
      throw new Error('账户不存在');
    }
    
    // 删除账户数据
    this.accounts.delete(accountId);
    
    // 如果删除的是当前账户，切换到第一个账户
    if (this.currentAccount && this.currentAccount.id === accountId) {
      const firstAccount = this.accounts.values().next().value;
      if (firstAccount) {
        await this.switchAccount(firstAccount.id);
      } else {
        this.currentAccount = null;
      }
    }
    
    await this.saveAccounts();
  }

  // 生成账户ID
  generateAccountId() {
    return 'account_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  // 保存账户到本地存储
  async saveAccounts() {
    const accountsData = {};
    for (const [id, account] of this.accounts) {
      accountsData[id] = {
        ...account,
        token: await this.saveToken(account.token)
      };
    }
    
    try {
      localStorage.setItem('simplenote_accounts', JSON.stringify(accountsData));
    } catch (error) {
      if (error.name === 'QuotaExceededError') {
        console.warn('存储空间不足，清理旧数据...');
        await this.cleanupStorage();
        // 重试保存
        localStorage.setItem('simplenote_accounts', JSON.stringify(accountsData));
      } else {
        throw error;
      }
    }
  }

  // 清理存储空间
  async cleanupStorage() {
    // 清理旧的笔记数据
    const keys = Object.keys(localStorage);
    const noteKeys = keys.filter(key => key.startsWith('simplenote_notes_'));
    
    // 按时间排序，删除最旧的笔记
    const noteData = noteKeys.map(key => {
      try {
        const data = JSON.parse(localStorage.getItem(key));
        return { key, timestamp: data.lastModified || 0 };
      } catch {
        return { key, timestamp: 0 };
      }
    }).sort((a, b) => a.timestamp - b.timestamp);
    
    // 删除一半的旧笔记
    const toDelete = noteData.slice(0, Math.floor(noteData.length / 2));
    toDelete.forEach(({ key }) => {
      localStorage.removeItem(key);
    });
    
    console.log(`清理了 ${toDelete.length} 个旧笔记`);
  }

  // 从本地存储加载账户
  loadAccounts() {
    const accountsData = localStorage.getItem('simplenote_accounts');
    if (accountsData) {
      const parsed = JSON.parse(accountsData);
      for (const [id, account] of Object.entries(parsed)) {
        this.accounts.set(id, account);
      }
    }
  }

  // 保存令牌（直接保存，不加密）
  async saveToken(token) {
    return token; // 直接返回，不进行任何处理
  }

  // 获取令牌（直接返回）
  async getToken(savedToken) {
    return savedToken; // 直接返回，不进行任何处理
  }

  // 保存当前账户数据
  async saveCurrentAccountData() {
    if (!this.currentAccount) return;
    
    try {
      // 保存到本地存储
      const notesData = JSON.stringify(this.currentAccount.notes);
      localStorage.setItem(`simplenote_notes_${this.currentAccount.id}`, notesData);
    } catch (error) {
      if (error.name === 'QuotaExceededError') {
        console.warn('存储空间不足，清理旧数据...');
        await this.cleanupStorage();
        // 重试保存
        const notesData = JSON.stringify(this.currentAccount.notes);
        localStorage.setItem(`simplenote_notes_${this.currentAccount.id}`, notesData);
      } else {
        throw error;
      }
    }
  }

  // 加载账户数据
  async loadAccountData(account) {
    // 从本地存储加载
    const notesData = localStorage.getItem(`simplenote_notes_${account.id}`);
    if (notesData) {
      account.notes = JSON.parse(notesData);
    }
  }
}

// 笔记管理类
class NoteManager {
  constructor(accountManager) {
    this.accountManager = accountManager;
    this.crypto = new CryptoUtils();
    this.currentNote = null;
    this.maxNoteSize = 100000; // 单个笔记最大字符数（约100KB）
    this.maxFileSize = 500000; // 单个文件最大字符数（约500KB）
  }

  // 创建笔记
  async createNote(title = '', content = '') {
    if (!this.accountManager.currentAccount) {
      throw new Error('请先选择账户');
    }
    
    // 检查笔记大小
    if (content.length > this.maxNoteSize) {
      throw new Error(`笔记内容过长，最大支持 ${this.maxNoteSize} 个字符`);
    }
    
    // 不再限制笔记数量
    
    const id = this.generateNoteId();
    const note = {
      id,
      title,
      content,
      createdAt: Date.now(),
      updatedAt: Date.now()
    };
    
    // 加密笔记
    const encryptedNote = await this.encryptNote(note);
    
    this.accountManager.currentAccount.notes[id] = encryptedNote;
    await this.saveNotes();
    
    return note;
  }

  // 更新笔记
  async updateNote(id, title, content) {
    if (!this.accountManager.currentAccount) {
      throw new Error('请先选择账户');
    }
    
    const note = {
      id,
      title,
      content,
      updatedAt: Date.now()
    };
    
    // 加密笔记
    const encryptedNote = await this.encryptNote(note);
    
    this.accountManager.currentAccount.notes[id] = encryptedNote;
    await this.saveNotes();
    
    return note;
  }

  // 删除笔记
  async deleteNote(id) {
    if (!this.accountManager.currentAccount) {
      throw new Error('请先选择账户');
    }
    
    delete this.accountManager.currentAccount.notes[id];
    await this.saveNotes();
  }

  // 获取笔记
  async getNote(id) {
    if (!this.accountManager.currentAccount) {
      throw new Error('请先选择账户');
    }
    
    const encryptedNote = this.accountManager.currentAccount.notes[id];
    if (!encryptedNote) {
      return null;
    }
    
    return await this.decryptNote(encryptedNote);
  }

  // 获取所有笔记
  async getAllNotes() {
    if (!this.accountManager.currentAccount) {
      return {};
    }
    
    const notes = {};
    for (const [id, encryptedNote] of Object.entries(this.accountManager.currentAccount.notes)) {
      try {
        notes[id] = await this.decryptNote(encryptedNote);
      } catch (error) {
        console.error(`解密笔记 ${id} 失败:`, error);
        // 创建解密失败的笔记占位符
        notes[id] = {
          id: id,
          title: '[解密失败] 无法读取此笔记',
          content: '此笔记可能使用了不同的加密密钥，无法解密。\n\n可能的原因：\n1. 使用了不同版本的应用程序\n2. 修改了编译时密钥\n3. 数据损坏\n\n如需恢复，请检查加密密钥设置。',
          createdAt: encryptedNote.createdAt || Date.now(),
          updatedAt: encryptedNote.updatedAt || Date.now(),
          isDecryptFailed: true,
          originalEncryptedNote: encryptedNote
        };
      }
    }
    return notes;
  }

  // 搜索笔记
  async searchNotes(query) {
    const notes = await this.getAllNotes();
    const results = {};
    
    for (const [id, note] of Object.entries(notes)) {
      if (note.title.toLowerCase().includes(query.toLowerCase()) ||
          note.content.toLowerCase().includes(query.toLowerCase())) {
        results[id] = note;
      }
    }
    
    return results;
  }

  // 加密笔记
  async encryptNote(note) {
    const account = this.accountManager.currentAccount;
    const key = await this.crypto.generateUserKey(account.platform);
    
    const encryptedTitle = await this.crypto.encryptText(note.title, key);
    const encryptedContent = await this.crypto.encryptText(note.content, key);
    
    return {
      id: note.id,
      title: encryptedTitle,
      content: encryptedContent,
      createdAt: note.createdAt,
      updatedAt: note.updatedAt,
      encrypted: true
    };
  }

  // 解密笔记
  async decryptNote(encryptedNote) {
    const account = this.accountManager.currentAccount;
    const key = await this.crypto.generateUserKey(account.platform);
    
    const title = await this.crypto.decryptText(encryptedNote.title, key);
    const content = await this.crypto.decryptText(encryptedNote.content, key);
    
    return {
      id: encryptedNote.id,
      title,
      content,
      createdAt: encryptedNote.createdAt,
      updatedAt: encryptedNote.updatedAt
    };
  }

  // 生成笔记ID
  generateNoteId() {
    return 'note_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  // 保存笔记
  async saveNotes() {
    await this.accountManager.saveCurrentAccountData();
  }


  // 获取存储统计信息
  getStorageStats() {
    if (!this.accountManager.currentAccount) {
      return { noteCount: 0, totalSize: 0 };
    }
    
    const notes = this.accountManager.currentAccount.notes;
    const noteCount = Object.keys(notes).length;
    
    // 估算存储大小（加密后的数据通常比原文大）
    let totalSize = 0;
    for (const note of Object.values(notes)) {
      totalSize += JSON.stringify(note).length;
    }
    
    // 估算文件数量
    const fileCount = Math.ceil(totalSize / this.maxFileSize);
    
    return {
      noteCount,
      totalSize,
      fileCount,
      maxNoteSize: this.maxNoteSize,
      maxFileSize: this.maxFileSize
    };
  }
}

// 同步管理类
class SyncManager {
  constructor(accountManager, noteManager) {
    this.accountManager = accountManager;
    this.noteManager = noteManager;
    this.syncInterval = null;
    this.isSyncing = false;
  }

  // 开始自动同步
  startAutoSync() {
    if (this.syncInterval) {
      clearInterval(this.syncInterval);
    }
    
    const account = this.accountManager.currentAccount;
    if (account && account.settings.autoSync) {
      this.syncInterval = setInterval(() => {
        this.syncToGit();
      }, account.settings.syncInterval);
    }
  }

  // 停止自动同步
  stopAutoSync() {
    if (this.syncInterval) {
      clearInterval(this.syncInterval);
      this.syncInterval = null;
    }
  }

  // 同步到Git
  async syncToGit() {
    if (this.isSyncing) {
      return;
    }
    
    const account = this.accountManager.currentAccount;
    if (!account) {
      throw new Error('请先选择账户');
    }
    
    this.isSyncing = true;
    
    try {
      // 检查网络状态
      if (!navigator.onLine) {
        throw new Error('网络连接已断开，请检查网络后重试');
      }
      
      const token = await this.accountManager.getToken(account.token);
      console.log('同步时使用的令牌信息:', {
        platform: account.platform,
        username: account.username,
        repo: account.repo,
        tokenLength: token.length,
        tokenPrefix: token.substring(0, 10) + '...'
      });
      
      const adapter = new GitPlatformAdapter(
        account.platform,
        token,
        account.username,
        account.repo
      );
      
      await adapter.syncNotes(account.notes);
      
      this.showNotification('同步成功', 'success');
    } catch (error) {
      console.error('同步失败:', error);
      
      // 提供更友好的错误信息
      let errorMessage = error.message;
      
      // 如果错误信息已经包含具体的错误描述，直接使用
      if (error.message.includes('认证失败') || 
          error.message.includes('权限不足') || 
          error.message.includes('仓库不存在') ||
          error.message.includes('网络连接失败')) {
        errorMessage = error.message;
      } else if (error.message.includes('Failed to fetch')) {
        errorMessage = '网络连接失败，请检查网络设置或稍后重试';
      } else if (error.message.includes('401')) {
        errorMessage = '认证失败，请检查访问令牌是否有效';
      } else if (error.message.includes('403')) {
        errorMessage = '权限不足，请检查仓库访问权限';
      } else if (error.message.includes('404')) {
        errorMessage = '仓库不存在，请检查仓库名称';
      }
      
      this.showNotification('同步失败: ' + errorMessage, 'error');
    } finally {
      this.isSyncing = false;
    }
  }

  // 从Git拉取
  async pullFromGit() {
    const account = this.accountManager.currentAccount;
    if (!account) {
      throw new Error('请先选择账户');
    }
    
    try {
      const adapter = new GitPlatformAdapter(
        account.platform,
        await this.accountManager.getToken(account.token),
        account.username,
        account.repo
      );
      
      const remoteNotes = await adapter.getNotes();
      
      // 合并远程笔记
      account.notes = { ...account.notes, ...remoteNotes };
      await this.accountManager.saveCurrentAccountData();
      
      this.showNotification('拉取成功', 'success');
    } catch (error) {
      console.error('拉取失败:', error);
      this.showNotification('拉取失败: ' + error.message, 'error');
    }
  }

  // 显示通知
  showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    const container = document.getElementById('notifications');
    container.appendChild(notification);
    
    setTimeout(() => {
      notification.remove();
    }, 3000);
  }
}

// 主应用类
class SimpleNoteApp {
  constructor() {
    this.accountManager = new AccountManager();
    this.noteManager = new NoteManager(this.accountManager);
    this.syncManager = new SyncManager(this.accountManager, this.noteManager);
    this.currentView = 'login';
    this.isSaving = false; // 防止重复保存标志
    this.lastSaveTime = 0; // 上次保存时间
    this.saveInterval = 1000; // 保存间隔1秒
    this.init();
  }

  // 初始化应用
  async init() {
    console.log('SimpleNote 初始化中...', APP_CONFIG);
    
    // 注册 Service Worker
    if ('serviceWorker' in navigator) {
      try {
        await navigator.serviceWorker.register('/sw.js');
        console.log('Service Worker 注册成功');
      } catch (error) {
        console.error('Service Worker 注册失败:', error);
      }
    }
    
    // 绑定事件
    this.bindEvents();
    
    // 检查是否有已保存的账户
    if (this.accountManager.accounts.size > 0) {
      // 自动切换到最后一个使用的账户
      const lastUsedAccount = Array.from(this.accountManager.accounts.values())
        .sort((a, b) => b.lastUsed - a.lastUsed)[0];
      
      await this.switchToAccount(lastUsedAccount.id);
    } else {
      // 显示登录界面
      this.showLoginScreen();
    }
  }

  // 绑定事件
  bindEvents() {
    console.log('开始绑定事件...');
    
    // 登录按钮
    const loginBtn = document.getElementById('login-btn');
    if (loginBtn) {
      loginBtn.addEventListener('click', () => {
        this.handleLogin();
      });
      console.log('登录按钮事件绑定成功');
    } else {
      console.error('找不到登录按钮元素');
    }

    // 强制刷新缓存按钮（登录界面）
    const refreshCacheBtn = document.getElementById('refresh-cache-btn');
    if (refreshCacheBtn) {
      refreshCacheBtn.addEventListener('click', () => {
        this.refreshCache();
      });
      console.log('登录界面刷新缓存按钮事件绑定成功');
    } else {
      console.error('找不到登录界面刷新缓存按钮元素');
    }

    // 设置界面刷新缓存按钮
    const settingsRefreshCacheBtn = document.getElementById('settings-refresh-cache-btn');
    if (settingsRefreshCacheBtn) {
      settingsRefreshCacheBtn.addEventListener('click', () => {
        this.refreshCache();
      });
      console.log('设置界面刷新缓存按钮事件绑定成功');
    } else {
      console.error('找不到设置界面刷新缓存按钮元素');
    }

    // 菜单按钮（侧边栏切换）
    const menuBtn = document.getElementById('menu-btn');
    if (menuBtn) {
      menuBtn.addEventListener('click', () => {
        this.toggleSidebar();
      });
      console.log('菜单按钮事件绑定成功');
    } else {
      console.error('找不到菜单按钮元素');
    }
    
    // 移动端侧边栏遮罩层点击关闭
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    if (sidebarOverlay) {
      sidebarOverlay.addEventListener('click', () => {
        this.closeSidebar();
      });
      console.log('侧边栏遮罩层事件绑定成功');
    } else {
      console.error('找不到侧边栏遮罩层元素');
    }

    // 新建笔记按钮
    const newNoteBtn = document.getElementById('new-note-btn');
    if (newNoteBtn) {
      newNoteBtn.addEventListener('click', () => {
        this.createNewNote();
      });
      console.log('新建笔记按钮事件绑定成功');
    } else {
      console.error('找不到新建笔记按钮元素');
    }

    // 保存笔记按钮
    const saveNoteBtn = document.getElementById('save-note-btn');
    if (saveNoteBtn) {
      saveNoteBtn.addEventListener('click', () => {
        this.saveCurrentNote();
      });
      console.log('保存笔记按钮事件绑定成功');
    } else {
      console.error('找不到保存笔记按钮元素');
    }

    // 删除笔记按钮
    const deleteNoteBtn = document.getElementById('delete-note-btn');
    if (deleteNoteBtn) {
      deleteNoteBtn.addEventListener('click', () => {
        this.deleteCurrentNote();
      });
      console.log('删除笔记按钮事件绑定成功');
    } else {
      console.error('找不到删除笔记按钮元素');
    }

    // 同步按钮
    const syncBtn = document.getElementById('sync-btn');
    if (syncBtn) {
      syncBtn.addEventListener('click', () => {
        this.syncFromGit();
      });
      console.log('同步按钮事件绑定成功');
    } else {
      console.error('找不到同步按钮元素');
    }

    // 设置按钮
    const settingsBtn = document.getElementById('settings-btn');
    if (settingsBtn) {
      settingsBtn.addEventListener('click', () => {
        this.showSettings();
      });
      console.log('设置按钮事件绑定成功');
    } else {
      console.error('找不到设置按钮元素');
    }

    // 账户切换按钮
    const accountSwitcherBtn = document.getElementById('account-switcher-btn');
    if (accountSwitcherBtn) {
      accountSwitcherBtn.addEventListener('click', () => {
        this.showAccountSwitcher();
      });
      console.log('账户切换按钮事件绑定成功');
    } else {
      console.error('找不到账户切换按钮元素');
    }

    // 搜索输入框
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
      searchInput.addEventListener('input', (e) => {
        this.searchNotes(e.target.value);
      });
      console.log('搜索输入框事件绑定成功');
    } else {
      console.error('找不到搜索输入框元素');
    }

    // 笔记标题输入框
    const noteTitle = document.getElementById('note-title');
    if (noteTitle) {
      noteTitle.addEventListener('input', () => {
        this.autoSave();
      });
      console.log('笔记标题输入框事件绑定成功');
    } else {
      console.error('找不到笔记标题输入框元素');
    }

    // 笔记内容输入框
    const noteContent = document.getElementById('note-content');
    if (noteContent) {
      noteContent.addEventListener('input', () => {
        this.autoSave();
        this.updateWordCount();
      });
      console.log('笔记内容输入框事件绑定成功');
    } else {
      console.error('找不到笔记内容输入框元素');
    }

    // 模态框关闭按钮
    const closeSwitcher = document.getElementById('close-switcher');
    if (closeSwitcher) {
      closeSwitcher.addEventListener('click', () => {
        this.hideAccountSwitcher();
      });
      console.log('关闭切换器按钮事件绑定成功');
    } else {
      console.error('找不到关闭切换器按钮元素');
    }

    const closeSettings = document.getElementById('close-settings');
    if (closeSettings) {
      closeSettings.addEventListener('click', () => {
        this.hideSettings();
      });
      console.log('关闭设置按钮事件绑定成功');
    } else {
      console.error('找不到关闭设置按钮元素');
    }

    // 添加账户按钮
    const addAccountBtn = document.getElementById('add-account-btn');
    if (addAccountBtn) {
      addAccountBtn.addEventListener('click', () => {
        this.showAddAccountModal();
      });
      console.log('添加账户按钮事件绑定成功');
    } else {
      console.error('找不到添加账户按钮元素');
    }

    // 关闭添加账户模态框
    const closeAddAccount = document.getElementById('close-add-account');
    if (closeAddAccount) {
      closeAddAccount.addEventListener('click', () => {
        this.hideAddAccountModal();
      });
      console.log('关闭添加账户按钮事件绑定成功');
    } else {
      console.error('找不到关闭添加账户按钮元素');
    }

    const cancelAddAccount = document.getElementById('cancel-add-account');
    if (cancelAddAccount) {
      cancelAddAccount.addEventListener('click', () => {
        this.hideAddAccountModal();
      });
      console.log('取消添加账户按钮事件绑定成功');
    } else {
      console.error('找不到取消添加账户按钮元素');
    }

    // 保存账户按钮
    const saveAccount = document.getElementById('save-account');
    if (saveAccount) {
      saveAccount.addEventListener('click', () => {
        this.handleSaveAccount();
      });
      console.log('保存账户按钮事件绑定成功');
    } else {
      console.error('找不到保存账户按钮元素');
    }
    
    console.log('所有事件绑定完成');
  }

  // 处理登录
  async handleLogin() {
    const platformElement = document.querySelector('input[name="platform"]:checked');
    if (!platformElement) {
      this.showNotification('请选择 Git 平台', 'error');
      return;
    }
    
    const platform = platformElement.value;
    const token = document.getElementById('access-token').value;
    
    if (!token) {
      this.showNotification('请输入访问令牌', 'error');
      return;
    }
    
    if (!platform) {
      this.showNotification('请选择 Git 平台', 'error');
      return;
    }
    
    try {
      // 创建临时适配器验证令牌
      const tempAdapter = new GitPlatformAdapter(platform, token, '', '');
      const userInfo = await tempAdapter.validateToken();
      
      // 显示添加账户表单
      this.showAddAccountForm(platform, token, userInfo);
    } catch (error) {
      this.showNotification('登录失败: ' + error.message, 'error');
    }
  }

  // 切换侧边栏显示
  toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    
    if (sidebar) {
      // 检查是否为移动端
      const isMobile = window.innerWidth <= 768;
      
      if (isMobile) {
        // 移动端：使用 open 类和遮罩层
        const isOpen = sidebar.classList.contains('open');
        if (isOpen) {
          this.closeSidebar();
        } else {
          this.openSidebar();
        }
      } else {
        // 桌面端使用 hidden 类
        sidebar.classList.toggle('hidden');
      }
    }
  }
  
  // 打开侧边栏（移动端）
  openSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    
    if (window.innerWidth <= 768) {
      sidebar.classList.add('open');
      overlay.classList.add('active');
      document.body.style.overflow = 'hidden'; // 防止背景滚动
    }
  }
  
  // 关闭侧边栏（移动端）
  closeSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    
    sidebar.classList.remove('open');
    overlay.classList.remove('active');
    document.body.style.overflow = ''; // 恢复滚动
  }

  // 从Git同步数据
  async syncFromGit() {
    try {
      const account = this.accountManager.currentAccount;
      if (!account) {
        this.showNotification('请先选择账户', 'error');
        return;
      }

      this.showNotification('正在从远程同步数据...', 'info');

      // 检查网络状态
      if (!navigator.onLine) {
        throw new Error('网络连接已断开，请检查网络后重试');
      }

      const token = await this.accountManager.getToken(account.token);
      const adapter = new GitPlatformAdapter(
        account.platform,
        token,
        account.username,
        account.repo
      );

      // 从远程获取笔记
      const remoteNotes = await adapter.getNotes();
      
      // 合并远程笔记到本地（远程数据优先）
      account.notes = { ...account.notes, ...remoteNotes };
      await this.accountManager.saveCurrentAccountData();
      
      // 刷新界面
      this.loadNotes();
      
      this.showNotification(`同步成功，获取了 ${Object.keys(remoteNotes).length} 个笔记`, 'success');
    } catch (error) {
      console.error('从远程同步失败:', error);
      this.showNotification('同步失败: ' + error.message, 'error');
    }
  }

  // 强制刷新缓存
  async refreshCache() {
    try {
      this.showNotification('正在清理缓存（保留配置信息）...', 'info');
      
      // 清理Service Worker缓存
      if ('serviceWorker' in navigator) {
        const registrations = await navigator.serviceWorker.getRegistrations();
        for (let registration of registrations) {
          await registration.unregister();
        }
      }
      
      // 清理浏览器缓存
      if ('caches' in window) {
        const cacheNames = await caches.keys();
        await Promise.all(
          cacheNames.map(cacheName => caches.delete(cacheName))
        );
      }
      
      // 清理localStorage（保留配置信息）
      const keys = Object.keys(localStorage);
      keys.forEach(key => {
        // 只清理笔记数据和临时数据，保留账户配置和设置
        if (key.startsWith('simplenote_notes_') || 
            key.startsWith('simplenote_temp_') ||
            key.startsWith('simplenote_cache_')) {
          localStorage.removeItem(key);
        }
      });
      
      // 清理sessionStorage
      sessionStorage.clear();
      
      // 清理IndexedDB（如果存在）
      if ('indexedDB' in window) {
        try {
          const databases = await indexedDB.databases();
          await Promise.all(
            databases.map(db => {
              return new Promise((resolve, reject) => {
                const deleteReq = indexedDB.deleteDatabase(db.name);
                deleteReq.onsuccess = () => resolve();
                deleteReq.onerror = () => reject(deleteReq.error);
              });
            })
          );
        } catch (error) {
          console.warn('清理IndexedDB失败:', error);
        }
      }
      
      this.showNotification('缓存清理完成！配置信息已保留，页面将重新加载...', 'success');
      
      // 延迟重新加载页面
      setTimeout(() => {
        window.location.reload(true);
      }, 1500);
      
    } catch (error) {
      console.error('清理缓存失败:', error);
      this.showNotification('清理缓存失败: ' + error.message, 'error');
    }
  }

  // 显示添加账户表单
  showAddAccountForm(platform = null, token = null, userInfo = null) {
    // 预填充表单数据
    if (userInfo) {
      document.getElementById('account-name').value = userInfo.login;
      document.getElementById('git-username').value = userInfo.login;
    }
    if (token) {
      document.getElementById('git-token').value = token;
    }
    
    // 显示模态框
    this.showAddAccountModal();
  }

  // 显示添加账户模态框
  showAddAccountModal() {
    const modal = document.getElementById('add-account-modal');
    modal.style.display = 'block';
    this.makeModalDraggable(modal);
  }

  // 隐藏添加账户模态框
  hideAddAccountModal() {
    document.getElementById('add-account-modal').style.display = 'none';
    // 清空表单
    document.getElementById('add-account-form').reset();
  }

  // 处理保存账户
  async handleSaveAccount() {
    const accountName = document.getElementById('account-name').value;
    const username = document.getElementById('git-username').value;
    const repo = document.getElementById('git-repo').value;
    const token = document.getElementById('git-token').value;
    
    if (!accountName || !username || !repo || !token) {
      this.showNotification('请填写完整信息', 'error');
      return;
    }

    // 获取当前选择的平台
    const platformElement = document.querySelector('input[name="platform"]:checked');
    if (!platformElement) {
      this.showNotification('请选择 Git 平台', 'error');
      return;
    }
    const platform = platformElement.value;

    try {
      await this.createAccount(accountName, platform, token, username, repo);
      this.hideAddAccountModal();
    } catch (error) {
      this.showNotification('创建账户失败: ' + error.message, 'error');
    }
  }

  // 创建账户
  async createAccount(name, platform, token, username, repo) {
    try {
      const account = await this.accountManager.createAccount(name, platform, token, username, repo);
      await this.switchToAccount(account.id);
      this.showNotification('账户创建成功', 'success');
    } catch (error) {
      this.showNotification('创建账户失败: ' + error.message, 'error');
    }
  }

  // 切换到指定账户
  async switchToAccount(accountId) {
    try {
      const account = await this.accountManager.switchAccount(accountId);
      this.showMainApp();
      this.updateUIForAccount(account);
      this.loadNotes();
      
      // 自动从远程同步数据
      try {
        await this.syncFromGit();
      } catch (syncError) {
        console.warn('自动同步失败:', syncError);
        // 同步失败不影响账户切换，只显示警告
        this.showNotification('账户切换成功，但同步失败: ' + syncError.message, 'warning');
      }
      
      this.syncManager.startAutoSync();
    } catch (error) {
      this.showNotification('切换账户失败: ' + error.message, 'error');
    }
  }

  // 显示主应用
  showMainApp() {
    document.getElementById('loading-screen').style.display = 'none';
    document.getElementById('login-screen').style.display = 'none';
    document.getElementById('main-app').style.display = 'flex';
    this.currentView = 'main';
  }

  // 显示登录界面
  showLoginScreen() {
    document.getElementById('loading-screen').style.display = 'none';
    document.getElementById('login-screen').style.display = 'flex';
    document.getElementById('main-app').style.display = 'none';
    this.currentView = 'login';
  }

  // 更新界面以反映当前账户
  updateUIForAccount(account) {
    // 导航中显示仓库名
    document.getElementById('current-account-name').textContent = account.repo;
    document.title = `${account.repo} - SimpleNote`;
  }

  // 加载笔记列表
  async loadNotes() {
    const notes = await this.noteManager.getAllNotes();
    this.renderNoteList(notes);
  }

  // 渲染笔记列表
  renderNoteList(notes) {
    const noteList = document.getElementById('note-list');
    noteList.innerHTML = '';
    
    const sortedNotes = Object.values(notes).sort((a, b) => b.updatedAt - a.updatedAt);
    
    sortedNotes.forEach(note => {
      const noteElement = document.createElement('div');
      noteElement.className = note.isDecryptFailed ? 'note-item decrypt-failed' : 'note-item';
      noteElement.dataset.noteId = note.id;
      
      if (note.isDecryptFailed) {
        noteElement.innerHTML = `
          <div class="note-item-title">${note.title}</div>
          <div class="note-item-preview">${note.content.substring(0, 100)}${note.content.length > 100 ? '...' : ''}</div>
          <div class="note-item-meta">
            ${new Date(note.updatedAt).toLocaleString()}
            <button class="btn btn-danger delete-failed-note" data-note-id="${note.id}" style="margin-left: 10px;">
              删除
            </button>
          </div>
        `;
        
        // 为删除按钮添加事件监听器
        const deleteBtn = noteElement.querySelector('.delete-failed-note');
        deleteBtn.addEventListener('click', (e) => {
          e.stopPropagation(); // 阻止触发选择笔记事件
          this.deleteFailedNote(note.id);
        });
      } else {
        noteElement.innerHTML = `
          <div class="note-item-title">${note.title || '无标题'}</div>
          <div class="note-item-preview">${note.content.substring(0, 100)}${note.content.length > 100 ? '...' : ''}</div>
          <div class="note-item-meta">${new Date(note.updatedAt).toLocaleString()}</div>
        `;
      }
      
      noteElement.addEventListener('click', () => {
        if (!note.isDecryptFailed) {
          this.selectNote(note.id);
        }
      });
      
      noteList.appendChild(noteElement);
    });
  }

  // 选择笔记
  async selectNote(noteId) {
    try {
      const note = await this.noteManager.getNote(noteId);
      if (note) {
        this.currentNote = note;
        this.loadNoteToEditor(note);
        this.updateNoteSelection(noteId);
      }
    } catch (error) {
      this.showNotification('加载笔记失败: ' + error.message, 'error');
    }
  }

  // 加载笔记到编辑器
  loadNoteToEditor(note) {
    document.getElementById('note-title').value = note.title;
    document.getElementById('note-content').value = note.content;
    this.updateWordCount(); // 更新字数统计
  }

  // 删除解密失败的笔记
  async deleteFailedNote(noteId) {
    const confirmed = await this.showConfirmDialog(
      '删除解密失败的笔记',
      '确定要删除这个解密失败的笔记吗？删除后无法恢复。'
    );
    
    if (confirmed) {
      try {
        // 从账户数据中删除
        delete this.accountManager.currentAccount.notes[noteId];
        await this.accountManager.saveCurrentAccountData();
        
        // 刷新笔记列表
        this.loadNotes();
        
        this.showNotification('解密失败的笔记已删除', 'success');
      } catch (error) {
        this.showNotification('删除失败: ' + error.message, 'error');
      }
    }
  }

  // 更新笔记选择状态
  updateNoteSelection(noteId) {
    document.querySelectorAll('.note-item').forEach(item => {
      item.classList.remove('active');
    });
    
    const selectedItem = document.querySelector(`[data-note-id="${noteId}"]`);
    if (selectedItem) {
      selectedItem.classList.add('active');
    }
  }

  // 创建新笔记
  async createNewNote() {
    try {
      const note = await this.noteManager.createNote('新笔记', '');
      this.currentNote = note;
      this.loadNoteToEditor(note);
      this.loadNotes();
      this.updateNoteSelection(note.id);
    } catch (error) {
      this.showNotification('创建笔记失败: ' + error.message, 'error');
    }
  }

  // 保存当前笔记
  async saveCurrentNote() {
    // 防止重复保存
    if (this.isSaving) {
      console.log('正在保存中，跳过重复保存请求');
      return;
    }
    
    // 检查保存间隔
    const now = Date.now();
    const timeSinceLastSave = now - this.lastSaveTime;
    if (timeSinceLastSave < this.saveInterval) {
      const remainingTime = Math.ceil((this.saveInterval - timeSinceLastSave) / 1000);
      this.showNotification(`请等待 ${remainingTime} 秒后再保存`, 'warning');
      return;
    }
    
    this.isSaving = true;
    
    const title = document.getElementById('note-title').value;
    const content = document.getElementById('note-content').value;
    
    // 如果没有内容，不保存
    if (!content.trim()) {
      this.showNotification('请输入笔记内容', 'error');
      this.isSaving = false;
      return;
    }
    
    // 如果没有标题，使用内容第一行作为标题
    const finalTitle = title.trim() || this.extractTitleFromContent(content);
    
    try {
      if (this.currentNote) {
        // 更新现有笔记
        await this.noteManager.updateNote(this.currentNote.id, finalTitle, content);
        this.currentNote.title = finalTitle;
        this.currentNote.content = content;
        this.currentNote.updatedAt = Date.now();
      } else {
        // 创建新笔记
        const newNote = await this.noteManager.createNote(finalTitle, content);
        this.currentNote = newNote;
      }
      
      // 更新标题输入框
      document.getElementById('note-title').value = finalTitle;
      this.loadNotes();
      
      // 自动同步到Git
      try {
        await this.syncManager.syncToGit();
        // 更新最后保存时间
        this.lastSaveTime = Date.now();
        // 根据是否为新笔记显示不同的成功消息
        const successMsg = this.currentNote && this.currentNote.id ? '笔记已更新' : '新笔记已创建';
        this.showNotification(successMsg, 'success');
      } catch (syncError) {
        console.warn('自动同步失败:', syncError);
        // 提取错误信息，避免重复的"同步失败:"前缀
        let errorMsg = syncError.message;
        if (errorMsg.startsWith('同步失败: ')) {
          errorMsg = errorMsg.substring(5); // 移除"同步失败: "前缀
        }
        // 根据是否为新笔记显示不同的消息
        const localMsg = this.currentNote && this.currentNote.id ? '笔记已更新' : '新笔记已创建';
        this.showNotification(`${localMsg}，但同步失败: ${errorMsg}`, 'error');
      }
    } catch (error) {
      console.error('保存笔记失败:', error);
      this.showNotification('保存失败: ' + error.message, 'error');
    } finally {
      this.isSaving = false;
    }
  }

  // 从内容中提取标题（第一行）
  extractTitleFromContent(content) {
    const lines = content.trim().split('\n');
    const firstLine = lines[0].trim();
    
    // 如果第一行太长，截取前50个字符
    if (firstLine.length > 50) {
      return firstLine.substring(0, 50) + '...';
    }
    
    return firstLine || '无标题笔记';
  }

  // 删除当前笔记
  async deleteCurrentNote() {
    if (!this.currentNote) {
      this.showNotification('没有选中的笔记', 'error');
      return;
    }
    
    const confirmed = await this.showConfirmDialog(
      '删除笔记',
      '确定要删除这个笔记吗？'
    );
    
    if (confirmed) {
      try {
        await this.noteManager.deleteNote(this.currentNote.id);
        this.currentNote = null;
        document.getElementById('note-title').value = '';
        document.getElementById('note-content').value = '';
        this.loadNotes();
        this.showNotification('删除成功', 'success');
        
        // 自动同步到Git
        try {
          await this.syncManager.syncToGit();
          // 移除多余的同步成功提示
        } catch (syncError) {
          console.warn('自动同步失败:', syncError);
          // 提取错误信息，避免重复的"同步失败:"前缀
          let errorMsg = syncError.message;
          if (errorMsg.startsWith('同步失败: ')) {
            errorMsg = errorMsg.substring(5); // 移除"同步失败: "前缀
          }
          this.showNotification('本地删除成功，但同步失败: ' + errorMsg, 'error');
        }
      } catch (error) {
        this.showNotification('删除失败: ' + error.message, 'error');
      }
    }
  }

  // 自动保存
  autoSave() {
    if (this.autoSaveTimeout) {
      clearTimeout(this.autoSaveTimeout);
    }
    
    this.autoSaveTimeout = setTimeout(() => {
      if (this.currentNote) {
        this.saveCurrentNote();
      }
    }, 2000); // 2秒后自动保存
  }

  // 搜索笔记
  async searchNotes(query) {
    if (!query.trim()) {
      this.loadNotes();
      return;
    }
    
    try {
      const notes = await this.noteManager.searchNotes(query);
      this.renderNoteList(notes);
    } catch (error) {
      this.showNotification('搜索失败: ' + error.message, 'error');
    }
  }

  // 显示账户切换器
  showAccountSwitcher() {
    const modal = document.getElementById('account-switcher');
    const accountList = document.getElementById('account-list');
    
    accountList.innerHTML = '';
    
    this.accountManager.accounts.forEach(account => {
      const accountElement = document.createElement('div');
      accountElement.className = 'account-item';
      accountElement.dataset.accountId = account.id;
      
      accountElement.innerHTML = `
        <div class="account-info">
          <div class="account-avatar">${account.name.charAt(0).toUpperCase()}</div>
          <div class="account-details">
            <h4>${account.name}</h4>
            <p>${account.platform} • ${new Date(account.lastUsed).toLocaleDateString()}</p>
          </div>
        </div>
        <div class="account-actions">
          <button class="btn btn-primary switch-account-btn">切换</button>
        </div>
      `;
      
      accountElement.querySelector('.switch-account-btn').addEventListener('click', () => {
        this.switchToAccount(account.id);
        this.hideAccountSwitcher();
      });
      
      accountList.appendChild(accountElement);
    });
    
    modal.style.display = 'block';
  }

  // 隐藏账户切换器
  hideAccountSwitcher() {
    document.getElementById('account-switcher').style.display = 'none';
  }

  // 显示设置
  showSettings() {
    const modal = document.getElementById('settings-modal');
    modal.style.display = 'block';
    this.loadSettings();
    this.bindSettingsEvents();
    this.makeModalDraggable(modal);
    
    // 默认激活账户管理标签页
    this.switchSettingsTab('accounts');
  }

  // 隐藏设置
  hideSettings() {
    document.getElementById('settings-modal').style.display = 'none';
  }

  // 绑定设置相关事件
  bindSettingsEvents() {
    // 标签页切换
    const tabBtns = document.querySelectorAll('.tab-btn');
    tabBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        const tabName = btn.dataset.tab;
        this.switchSettingsTab(tabName);
      });
    });

    // 自动同步设置
    const autoSyncCheckbox = document.getElementById('auto-sync');
    if (autoSyncCheckbox) {
      autoSyncCheckbox.addEventListener('change', (e) => {
        this.updateSetting('autoSync', e.target.checked);
      });
    }

    // 同步间隔设置
    const syncIntervalInput = document.getElementById('sync-interval');
    if (syncIntervalInput) {
      syncIntervalInput.addEventListener('change', (e) => {
        this.updateSetting('syncInterval', parseInt(e.target.value) * 60000); // 转换为毫秒
      });
    }

    // 主题设置
    const themeSelect = document.getElementById('theme-select');
    if (themeSelect) {
      themeSelect.addEventListener('change', (e) => {
        this.updateSetting('theme', e.target.value);
        this.applyTheme(e.target.value);
      });
    }

    // 字体大小设置
    const fontSizeInput = document.getElementById('font-size');
    if (fontSizeInput) {
      fontSizeInput.addEventListener('input', (e) => {
        const size = parseInt(e.target.value);
        const fontSizeValue = document.getElementById('font-size-value');
        if (fontSizeValue) {
          fontSizeValue.textContent = `${size}px`;
        }
      });
      
      fontSizeInput.addEventListener('change', (e) => {
        const size = parseInt(e.target.value);
        this.updateSetting('fontSize', size);
        this.applyFontSize(size);
      });
    }
  }

  // 切换设置标签页
  switchSettingsTab(tabName) {
    // 移除所有活动状态
    document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

    // 激活选中的标签页
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
    document.getElementById(`${tabName}-tab`).classList.add('active');

    // 如果是账户管理标签页，刷新账户列表
    if (tabName === 'accounts') {
      this.renderAccountManagement();
    }
  }

  // 加载设置
  loadSettings() {
    const account = this.accountManager.currentAccount;
    if (!account) return;

    const settings = account.settings;

    // 加载自动同步设置
    const autoSyncCheckbox = document.getElementById('auto-sync');
    if (autoSyncCheckbox) {
      autoSyncCheckbox.checked = settings.autoSync;
    }

    // 加载同步间隔设置
    const syncIntervalInput = document.getElementById('sync-interval');
    if (syncIntervalInput) {
      syncIntervalInput.value = settings.syncInterval / 60000; // 转换为分钟
    }

    // 加载主题设置
    const themeSelect = document.getElementById('theme-select');
    if (themeSelect) {
      themeSelect.value = settings.theme;
    }

    // 加载字体大小设置
    const fontSizeInput = document.getElementById('font-size');
    if (fontSizeInput) {
      fontSizeInput.value = settings.fontSize;
      const fontSizeValue = document.getElementById('font-size-value');
      if (fontSizeValue) {
        fontSizeValue.textContent = `${settings.fontSize}px`;
      }
    }
  }

  // 更新设置
  async updateSetting(key, value) {
    const account = this.accountManager.currentAccount;
    if (!account) return;

    account.settings[key] = value;
    await this.accountManager.saveAccounts();

    // 如果是自动同步设置，重新启动自动同步
    if (key === 'autoSync' || key === 'syncInterval') {
      this.stopAutoSync();
      this.startAutoSync();
    }

    this.showNotification('设置已保存', 'success');
  }

  // 应用主题
  applyTheme(theme) {
    document.body.className = `theme-${theme}`;
  }

  // 应用字体大小
  applyFontSize(size) {
    document.documentElement.style.setProperty('--font-size', `${size}px`);
    // 同时应用到编辑器
    const editor = document.getElementById('note-content');
    if (editor) {
      editor.style.fontSize = `${size}px`;
    }
  }

  // 更新字数统计
  updateWordCount() {
    const textarea = document.getElementById('note-content');
    if (!textarea) return;
    
    // 获取或创建字数统计元素
    let wordCountElement = document.getElementById('word-count');
    if (!wordCountElement) {
      wordCountElement = document.createElement('div');
      wordCountElement.id = 'word-count';
      wordCountElement.className = 'word-count';
      wordCountElement.style.cssText = `
        position: absolute;
        bottom: 6px;
        right: 8px;
        font-size: 0.7rem;
        color: rgba(255, 255, 255, 0.5);
        background: rgba(0, 0, 0, 0.2);
        padding: 1px 4px;
        border-radius: 3px;
        backdrop-filter: blur(3px);
        pointer-events: none;
        z-index: 10;
        opacity: 0;
        transition: opacity 0.2s ease;
      `;
      textarea.parentNode.appendChild(wordCountElement);
    }
    
    const text = textarea.value;
    const charCount = text.length;
    const lineCount = text.split('\n').length;
    const wordCount = text.trim() ? text.trim().split(/\s+/).length : 0;
    const paragraphCount = text.split('\n\n').filter(p => p.trim()).length;
    
    // 根据内容长度选择显示格式
    if (charCount === 0) {
      wordCountElement.textContent = '';
      wordCountElement.style.opacity = '0';
    } else {
      if (charCount < 100) {
        wordCountElement.textContent = `${charCount}字`;
      } else if (charCount < 1000) {
        wordCountElement.textContent = `${charCount}字 / ${lineCount}行`;
      } else {
        wordCountElement.textContent = `${charCount}字 / ${wordCount}词 / ${lineCount}行`;
      }
      wordCountElement.style.opacity = '1';
    }
  }

  // 渲染账户管理界面
  renderAccountManagement() {
    const container = document.getElementById('account-management');
    if (!container) return;

    const accounts = Array.from(this.accountManager.accounts.values());
    
    let html = '';
    
    if (accounts.length === 0) {
      html = '<p>暂无账户</p>';
    } else {
      html = accounts.map(account => `
        <div class="account-item">
          <div class="account-info">
            <h5>${account.repo} (${account.username})</h5>
            <p>最后使用: ${new Date(account.lastUsed).toLocaleString()}</p>
          </div>
          <div class="account-actions">
            <button class="btn btn-primary" onclick="window.simpleNoteApp.switchToAccount('${account.id}')">切换</button>
            <button class="btn btn-danger" onclick="window.simpleNoteApp.deleteAccount('${account.id}')">删除</button>
          </div>
        </div>
      `).join('');
    }
    
    // 添加"添加新账户"按钮
    html += `
      <div class="account-item" style="border: 2px dashed var(--glass-border); background: transparent;">
        <div class="account-info" style="text-align: center; padding: var(--space-4);">
          <h5 style="margin-bottom: var(--space-2);">添加新账户</h5>
          <p style="color: var(--text-secondary); margin-bottom: var(--space-3);">添加新的Git平台账户</p>
        </div>
        <div class="account-actions">
          <button class="btn btn-primary" onclick="window.simpleNoteApp.showAddAccountModal()">添加账户</button>
        </div>
      </div>
    `;
    
    container.innerHTML = html;
  }

  // 删除账户
  async deleteAccount(accountId) {
    const confirmed = await this.showConfirmDialog(
      '删除账户',
      '确定要删除这个账户吗？这将删除所有相关的笔记数据。'
    );
    
    if (confirmed) {
      await this.accountManager.deleteAccount(accountId);
      this.renderAccountManagement();
      this.showNotification('账户已删除', 'success');
    }
  }

  // 使模态框可拖拽
  makeModalDraggable(modal) {
    const modalContent = modal.querySelector('.modal-content');
    const modalHeader = modal.querySelector('.modal-header');
    
    if (!modalContent || !modalHeader) return;

    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;

    // 重置位置
    modalContent.style.transform = 'translate(0px, 0px)';
    xOffset = 0;
    yOffset = 0;

    // 鼠标按下事件
    modalHeader.addEventListener('mousedown', dragStart);
    modal.addEventListener('mousemove', drag);
    modal.addEventListener('mouseup', dragEnd);
    modal.addEventListener('mouseleave', dragEnd);

    // 触摸事件支持
    modalHeader.addEventListener('touchstart', dragStart);
    modal.addEventListener('touchmove', drag);
    modal.addEventListener('touchend', dragEnd);

    function dragStart(e) {
      if (e.type === 'touchstart') {
        initialX = e.touches[0].clientX - xOffset;
        initialY = e.touches[0].clientY - yOffset;
      } else {
        initialX = e.clientX - xOffset;
        initialY = e.clientY - yOffset;
      }

      if (e.target === modalHeader || modalHeader.contains(e.target)) {
        isDragging = true;
        modalHeader.style.cursor = 'grabbing';
      }
    }

    function drag(e) {
      if (isDragging) {
        e.preventDefault();

        if (e.type === 'touchmove') {
          currentX = e.touches[0].clientX - initialX;
          currentY = e.touches[0].clientY - initialY;
        } else {
          currentX = e.clientX - initialX;
          currentY = e.clientY - initialY;
        }

        xOffset = currentX;
        yOffset = currentY;

        modalContent.style.transform = `translate(${currentX}px, ${currentY}px)`;
      }
    }

    function dragEnd(e) {
      initialX = currentX;
      initialY = currentY;
      isDragging = false;
      modalHeader.style.cursor = 'grab';
    }

    // 设置初始光标样式
    modalHeader.style.cursor = 'grab';
  }

  // 显示确认对话框
  showConfirmDialog(title, message) {
    return new Promise((resolve) => {
      const modal = document.getElementById('confirm-modal');
      const titleElement = document.getElementById('confirm-title');
      const messageElement = document.getElementById('confirm-message');
      const okBtn = document.getElementById('confirm-ok');
      const cancelBtn = document.getElementById('confirm-cancel');
      const closeBtn = document.getElementById('close-confirm');
      
      // 设置内容
      titleElement.textContent = title;
      messageElement.textContent = message;
      
      // 显示模态框
      modal.style.display = 'block';
      this.makeModalDraggable(modal);
      
      // 清理之前的事件监听器
      const newOkBtn = okBtn.cloneNode(true);
      const newCancelBtn = cancelBtn.cloneNode(true);
      const newCloseBtn = closeBtn.cloneNode(true);
      
      okBtn.parentNode.replaceChild(newOkBtn, okBtn);
      cancelBtn.parentNode.replaceChild(newCancelBtn, cancelBtn);
      closeBtn.parentNode.replaceChild(newCloseBtn, closeBtn);
      
      // 添加新的事件监听器
      newOkBtn.addEventListener('click', () => {
        modal.style.display = 'none';
        resolve(true);
      });
      
      newCancelBtn.addEventListener('click', () => {
        modal.style.display = 'none';
        resolve(false);
      });
      
      newCloseBtn.addEventListener('click', () => {
        modal.style.display = 'none';
        resolve(false);
      });
      
      // 点击背景关闭
      modal.addEventListener('click', (e) => {
        if (e.target === modal) {
          modal.style.display = 'none';
          resolve(false);
        }
      });
    });
  }

  // 显示通知
  showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    const container = document.getElementById('notifications');
    container.appendChild(notification);
    
    setTimeout(() => {
      notification.remove();
    }, 3000);
  }
}

// 启动应用
document.addEventListener('DOMContentLoaded', () => {
  window.simpleNoteApp = new SimpleNoteApp();
});
